package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.entity.Users;
import com.itheima.wisdomnext.mapper.FollowMapper;
import com.itheima.wisdomnext.mapper.LikeMapper;
import com.itheima.wisdomnext.mapper.UserMapper;
import com.itheima.wisdomnext.service.UserService;
import com.itheima.wisdomnext.util.UserS_Util;
import com.itheima.wisdomnext.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;

@Service
public class UserServiceImpI implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private JwtUtil jwtUtil; // 使用 JwtUtil

    @Autowired
    private PasswordEncoder passwordEncoder;

    public String registerUser(Users users) {
        // 检查用户名是否已存在
        if (userMapper.existsByUsername(users.getUsername())) {
            UserS_Util.isTrue(true, ErrorCode.FAILED,"用户名已存在");
        }

        // 获取当前年份的最后一位数字
        int currentYearLastDigit = Integer.parseInt(String.valueOf(java.time.LocalDate.now().getYear()).substring(3));

        // 生成一个 5 位的随机数字
        Random random = new Random();
        int randomFiveDigit = 10000 + random.nextInt(90000);  // 生成一个 5 位数字

        // 组合当前年最后一位和随机 5 位数字
        int randomUserId = currentYearLastDigit * 100000 + randomFiveDigit;  // 拼接成新的 userId

        // 创建新用户
        Users user = new Users();
        user.setUserId(randomUserId);
        user.setUsername(users.getUsername());
        user.setPassword(passwordEncoder.encode(users.getPassword())); // 密码加密
        user.setAvatar(users.getAvatar());

        userMapper.insertUser(user);

        return "注册成功";
    }

    public String loginUser(Users users) {
        // 查找用户
        Users user = userMapper.findByUsername(users.getUsername());

        // 如果用户不存在，抛出异常
        if (user == null) {
            throw new IllegalArgumentException("Invalid username or password");
        }

        // 验证密码
        if (!passwordEncoder.matches(users.getPassword(), user.getPassword())) {
            throw new IllegalArgumentException("Invalid username or password");
        }

        // 获取 userId
        int userId = user.getUserId();
        String avatar = (user.getAvatar() != null && !user.getAvatar().isEmpty()) ? user.getAvatar() : "";

        // 使用 JwtUtil 生成 Token
        String token = jwtUtil.generateToken(user.getUsername()); // 生成并返回 JWT 令牌

        // 返回 JWT 和 userId
        return "Token: " + token + ", userId: " + userId +", avatar: " + avatar;
    }

    public UserDetails loadUserByUsername(String username) {
        // 从数据库或其他来源加载用户信息
        return User.builder()
                .username(username)
                .password("password") // 从数据库获取密码
                .roles("USER") // 设置用户角色
                .build();
    }

    // 更新用户信息
    public void updateUserInfo(Users users) {
        // 更新逻辑，允许更新昵称、手机号、头像和地址
        int rowsAffected = userMapper.updateUserInfo(users);
        if (rowsAffected <= 0) {
            UserS_Util.isTrue(true, ErrorCode.FAILED,"更新失败，用户不存在或无效数据");
        }
    }

    public Users getUserById(int userId) {
        return userMapper.getUserById(userId);
    }

    public int getLikeCountByUserId(int userId) {
        // 假设你有一个 likeMapper 来查询数据库
        return likeMapper.countLikesByUserId(userId);
    }

    public int getFollowerCountByUserId(int userId) {
        // 假设你有一个 followMapper 来查询数据库
        return followMapper.countFollowersByUserId(userId);
    }

    public int getFollowedCountByUserId(int userId) {
        // 假设你有一个 followMapper 来查询数据库
        return followMapper.countFollowedByUserId(userId);
    }


    public List<Users> getUserByIdPost(int userId) {
        return userMapper.getUserByIdPost(userId);
    }

    @Value("${file.upload-dir}") // 图片保存路径
    private String uploadDir;

    // 更新头像
    public String updateAvatar(int userId, MultipartFile avatar) {
        if (avatar != null && !avatar.isEmpty()) {
            try {
                // 获取原始文件名
                String fileName = avatar.getOriginalFilename();
                Path filePath = Paths.get(uploadDir, fileName);
                Files.createDirectories(filePath.getParent()); // 创建目录
                avatar.transferTo(filePath.toFile()); // 保存图片

                userMapper.updateAvatar(userId, filePath.toString());

                // 更新用户的头像路径到数据库
                return "头像上传成功";
            } catch (IOException e) {
                return "头像上传失败：" + e.getMessage();
            }
        } else {
            return "没有上传头像";
        }
    }

    @Override
    public List<Integer> getFollowedUserIds(int userId) {
        return userMapper.getFollowedUserIds(userId);
    }

    @Override
    public List<Users> getAllUsers() {
        return userMapper.findAllUsers(); // 调用 Mapper 方法
    }

}
